<?php
/**
 * 创建人 : Forpastime
 *
 * @link     http://hypercmf.com
 * @document https://hyperf.wiki
 * @contact  forpastime@qq.com
 * @git  https://gitee.com/hypercmf/hypercmf1.0.git
 */
namespace App\Controller\Aliyun;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Vod\Vod;
use App\Service\AlivodService;
use App\Utils\Result;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Annotation\AdminNode;
use Hyperf\HttpServer\Contract\RequestInterface;
use App\Middleware\Auth\AdminTokenMiddleware;
use App\Middleware\Auth\AdminPowerMiddleware;

use AlibabaCloud\Client\Profile\DefaultProfile;
use AlibabaCloud\Client\DefaultAcsClient;
use AlibabaCloud\Vod\V20170321\CreateUploadVideoRequest;

/**
 * @AdminNode(name="阿里云VOD",isMenu=1,style="layui-icon-play")
 * @Middlewares({
 *      @Middleware(AdminTokenMiddleware::class),
 *      @Middleware(AdminPowerMiddleware::class)
 * })
 *
 * @AutoController(prefix="admin/vod")
 * Class AlivodController
 * @package App\Controller\Admin
 */
class AlivodController
{
    const VOD_CLIENT_NAME='HyperCMFVOD';
    /**
     * @var AlivodService
     * @Inject()
     */
    protected $alivodService;

    /**
     * @var RequestInterface
     * @Inject()
     */
    protected $request;

    /**
     * @AdminNode(name="修改VOD基本信息")
     *
     */
    public function editVod()
    {
        $param = $this->request->all();
        if(!isset($param['id']) || empty($param['id'])){
            return Result::error('参数异常');
        }
        $res = $this->alivodService->editVodOne($param['id'],$param);
        return Result::return([],$res);
    }

    /**
     * @AdminNode(name="删除记录")
     *
     * @return mixed
     */
    public function delVod()
    {
        $param = $this->request->all();

        $ids = array_column($param['data'],'id');
        $res = $this->alivodService->delVodOne($ids);
        return Result::success();
    }

    /**
     * @AdminNode(name="Vod列表",isMenu="1")
     *
     * @return mixed
     */
    public function aliyunVod()
    {
        $param = $this->request->all();
        $where = [];
        if(isset($param['title'])&& $param['title']!=''){
            $where[] = ['title','like','%'.$param['title']];
        }
        if(isset($param['upload_status'])&& $param['upload_status']!=''){
            $where[] = ['upload_status','=',$param['upload_status']];
        }
        if(isset($param['status'])&& $param['status']!=''){
            $where[] = ['status','=',$param['status']];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $start = strtotime(explode('~',$param['created_at'])[0]);
            $end =  strtotime(explode('~',$param['created_at'])[1]);
            $where[] = ['created_at','>=',$start];
            $where[] = ['created_at','<=',$end];
        }
        $field = 'id,video_id,desc,category_id,title,m3u8,path,cover,created_at,status,upload_status,file_hash,quality,updated_at';
        $list = $this->alivodService->getVodList($where,$field,$param['limit']);

        return Result::success($list);
    }

    /**
     * @AdminNode(name="上传至vod")
     *
     * @return mixed|void
     */
    public function upload()
    {
        $param = $this->request->all();

        if(isset($param['opentype']) && $param['opentype']=='edit'){
            //修改

            if($this->request->isMethod('post')){
                unset($param['opentype']);
                $this->alivodService->editVodOne($param['id'],$param);

                return Result::success('操作成功');
            }else{
                $info = $this->alivodService->getVodOne([['id','=',$param['id']]]);

                return Result::success([
                    'info'=>$info,
                    'opentype'=>'edit'
                ]);
            }

        }else{
            //新增
            if($this->request->isMethod('post')){

                $info = [
                    'video_id'=>$param['videoId'],
                    'file_hash'=>$param['fileHash'],
                    'title'=>$param['title'],
                    'cover'=>$param['cover'],
                    'desc'=>$param['desc'],
                    'created_at'=>time(),
                    'quality'=>$param['quality']
                ];
                $res = $this->alivodService->addVodOne($info);

                if($res){
                    return Result::success();
                }else{
                    return Result::error('操作失败');
                }
            }
            $data = [
                'aliUserId' => env('userid'),
                'env'=>env('env')
            ];
            return Result::success($data);
        }
    }

    /**
     * @AdminNode(name="检查vod是否存在")
     *
     * 通过fileHash查看数据库是否存在已上传记录
     */
    public function checkExist()
    {
        //判断数据库是否有该视频信息，有直接返回，无则创建
        $param = $this->request->all();
        if(!isset($param['fileHash'])){
            return Result::error('参数异常，请重新尝试');
        }
        $video = $this->alivodService->getVodOne([['file_hash','=',$param['fileHash']],['quality','=',$param['quality']]],'id,title,quality');
        if($video){
            //视频已上传过
            return Result::error('文件【'.$video['title'].'】当前选择的转码清晰度已上传过,ID:'.$video['id'],'',['exist'=>1]);
        }
        return Result::success();
    }
    /**
     * @AdminNode(name="获取上传凭据")
     * 获取上传地址和凭证返回web 采用JavaScript上传
     */
    public function getUploadAuth(){

        $param = $this->request->all();

        $uploadInfo = $this->createUploadVideo(env('VOD_ACCESS_ID'), env('VOD_ACCESS_SECRET'),$param);
        //$uploadInfo['UploadAddress'] = str_replace(' ','+',$uploadInfo['UploadAddress']);
        $videoId = $uploadInfo['VideoId'];
        //$RequestId = $uploadInfo['RequestId'];
        $UploadAddress = $uploadInfo['UploadAddress'];
        $UploadAuth = $uploadInfo['UploadAuth'];
        $data = [
            'videoId' => $videoId,
            'UploadAddress' => $UploadAddress,
            'UploadAuth' => $UploadAuth
        ];
        return Result::success($data);

    }

    /**
     * @AdminNode(name="上传vod userid传递")
     *
     * @return mixed
     */
    public function getConfig()
    {
        return Result::success(['env'=>env('APP_ENV','dev'),'user_id'=>env('vod_userid')]);
    }

    /**
     * 获取音/视频上传地址和凭证
     * @param $param
     * @return array
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     */
    private function createUploadVideo($accessKeyId,$accessKeySecret,$param) {
        $regionId = 'cn-shanghai';  // 点播服务接入区域
        AlibabaCloud::accessKeyClient($accessKeyId,$accessKeySecret)
            ->regionId($regionId)
            ->connectTimeout(1)
            ->timeout(3)
            ->name(self::VOD_CLIENT_NAME)
            ->asDefaultClient();

        $request = Vod::v20170321()->createUploadVideo();

        if(!empty($param)){
            if(isset($param['quality'])){
                switch ($param['quality']){
                    case 2:
                        $templateId = env('vod_quality_gaoqing');
                        break;
                    case 3:
                        $templateId = env('vod_quality_chaoqing');
                        break;
                    case 4:
                        $templateId = env('vod_quality_2k');
                        break;
                    default:
                        $templateId = env('vod_quality_biaozhun');
                        break;
                }
                $request->withTemplateGroupId($templateId);

            }

            $callBackData = [
                'MessageCallback'=>[
                    'CallbackURL'=>env('vod_callback_url'),
                ],
                'Extend'=>[
                    'env'=>env('APP_ENV','dev')
                ]
            ];


            $request->withTitle($param['title'])
                ->withFileName($param['fileName'])
                ->withDescription($param['desc'])
                ->withCateId(isset($param['category_id'])?$param['category_id']:0)
                ->withCoverURL(isset($param['cover'])?$param['cover']:'');
            if(isset($param['tag'])){
                $request->withTags($param['tag']);
            }

            //用户信息，用于回调捕捉
            if(isset($param['userData'])){
                $callBackData['Extend'] = $param['userData'];
                $request->withUserData(json_encode($callBackData));
            }

        }
        $result = $request->request();
        return $result->toArray();
    }

}